import { ProForm, ProFormInstance, ProFormTreeSelect, QueryFilter } from '@/components/Pro/';
import { energyGenerationControllerGetChart as charData } from '@/services/ess/statisticElectricityGeneration';
import { useIntl } from '@umijs/max';
import { DatePicker, Spin } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { TreeNode } from '../help';

const TableList: React.FC<{
  dateType: number;
  deviceInfo: TreeNode;
}> = ({ dateType, deviceInfo }) => {
  // const deciceInfoCopy  = loadsh.cloneDeep(deviceInfo)
  const intl = useIntl();
  const [date, setDate] = useState<Dayjs>(dayjs());
  const formRef = useRef<ProFormInstance>();
  const chartRef = useRef();
  const [pageData, setPageData] = useState({});
  const [loading, setLoading] = useState(true);
  const [isEmpty, setEmpty] = useState(true);
  const selectedType = useRef(null);
  const treeInfo = useRef<API.DeviceInfo>(deviceInfo);
  const dateTypeStr = (dateType === 1 && 'day') || (dateType === 2 && 'month') || 'year';
  const dateTypeFormate =
    (dateType === 1 && 'YYYY-MM-DD') || (dateType === 2 && 'YYYY-MM-DD') || 'YYYY-MM-DD';
  const [areaFlag, setareaFlag] = useState<boolean>(false);
  const [dataType, setdataType] = useState<string>('1');
  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };

  useEffect(() => {
    chartRef?.current?.getEchartsInstance()?.resize();
  });

  useEffect(() => {
    if (deviceInfo && deviceInfo.length) {
      selectedType.current = deviceInfo[0]?.nodeType;
      treeInfo.current = setDisabled([deviceInfo[0]]);
      formRef?.current?.setFieldsValue({
        codes: deviceInfo[0]?.key,
      });

      formRef?.current?.submit();
    }
  }, [dateType, deviceInfo]);

  return (
    <div>
      <QueryFilter
        split
        formRef={formRef}
        onFinish={async (value) => {
          console.log('相应的', value);
          try {
            let parms = {
              ...value,
              date: dayjs(date).format(dateTypeFormate),
              dateType: dateTypeStr,
              dataType,
              areaFlag,
              ...(dataType === '1' ? { codes: '' } : {}), // 使用三元表达式添加 codes 字段
            };
            let reslut = await charData(parms);
            if (reslut?.success) {
              const data = reslut?.data;
              chartRef?.current?.getEchartsInstance()?.clear();
              setEmpty(!data?.xaxis?.length || !data?.yaxis?.length);
              setPageData({
                xData: data?.xaxis ?? [],
                yData: data?.yaxis ?? [],
              });
              setLoading(false);
            } else {
              chartRef?.current?.getEchartsInstance()?.clear();
            }
          } catch (error) {
            setLoading(false);
            setPageData({
              xData: [],
              yData: [],
            });
            chartRef?.current?.getEchartsInstance()?.clear();
          }
        }}
        onReset={() => {
          selectedType.current = deviceInfo[0]?.nodeType;
          treeInfo.current = setDisabled([deviceInfo[0]]);
          setdataType('1');
          setareaFlag(false);
          formRef?.current?.setFieldsValue({
            codes: [treeInfo.current[0].key],
          });

          setDate(dayjs());
          formRef?.current?.submit();
        }}
      >
        <ProForm.Item
          label={intl.formatMessage({
            id: 'statistics.income.select',
          })}
        >
          <DatePicker
            allowClear={false}
            value={date}
            onChange={(date) => {
              setDate(date);
            }}
            defaultValue={dayjs()}
            picker={dateTypeStr}
            disabledDate={(current) => {
              return current && current > moment().endOf('day');
            }}
            style={{ width: '100%' }}
          ></DatePicker>
        </ProForm.Item>
        <ProFormTreeSelect
          name="codes"
          label={intl.formatMessage({
            id: 'statistics.work.dimensions',
          })}
          initialValue={deviceInfo[0]?.key}
          fieldProps={{
            treeData: treeInfo?.current && treeInfo.current?.length ? treeInfo.current : deviceInfo,
            fieldNames: {
              label: 'deviceName',
              value: 'key',
              children: 'subDevices',
            },
            multiple: true,
            maxTagCount: 'responsive',
            showSearch: true,
            treeNodeFilterProp: 'deviceName',
            onSelect: (...args) => {
              let selectedOptions = args[1];
              if (selectedType.current === null && selectedOptions?.nodeType) {
                selectedType.current = selectedOptions?.nodeType;
                setareaFlag(selectedOptions?.nodeType === 'AREA');
                setdataType(
                  selectedOptions?.nodeType === 'ROOT'
                    ? '1'
                    : selectedOptions?.nodeType === 'AREA'
                    ? '3'
                    : '2',
                );
              }
              treeInfo.current = setDisabled([deviceInfo[0]]);
            },
            onChange: (...args) => {
              let selectedOptions = args[1];
              if (!selectedOptions.length) {
                //清除后不再做相应限制
                setareaFlag(false);
                setdataType('');
                selectedType.current = null;
                treeInfo.current = setDisabled([deviceInfo[0]]);
              }
            },
          }}
        ></ProFormTreeSelect>
      </QueryFilter>
      <Spin spinning={loading}>
        <ReactEcharts
          ref={chartRef}
          style={{ height: 400, marginTop: 20 }}
          option={{
            tooltip: {
              trigger: 'axis',
              show: !isEmpty,
              formatter: function (params) {
                console.log(params, '相应的参数');
                let text = `<div>
                ${
                  dateType === 3
                    ? params[0].axisValueLabel?.substring(0, params[0].axisValueLabel?.length - 3)
                    : params[0]?.axisValueLabel
                }<br/>`;
                (params || []).forEach((item) => {
                  text += `${item.marker}${item.seriesName}&nbsp;:&nbsp;&nbsp;${item.value ?? '-'}`;
                  if (item.value || item.value === 0) {
                    text += 'kWh<br/>';
                  } else {
                    text += '<br/>';
                  }
                });
                text += '</div>';
                return text;
              },
            },
            dataZoom: {
              type: 'inside',
            },
            legend: {
              top: 0,
              right: 0,
              icon: 'item',
            },
            grid: {
              left: 40,
              right: 5,
              top: 40,
              bottom: 15,
              containLabel: true,
              show: true,
              borderColor: 'transparent',
              backgroundColor: isEmpty ? 'transparent' : '#F8F9FA',
            },
            xAxis: [
              {
                type: 'category',
                name: false,
                nameTextStyle: {
                  color: '#222',
                },
                data: pageData.xData || [],
                axisTick: {
                  alignWithLabel: true,
                  show: true,
                  inside: true,
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisLabel: {
                  color: '#222',
                  formatter: function (value) {
                    if (dateType === 1) {
                      return value?.substring(0, 2);
                    } else if (dateType === 2) {
                      return value?.substring(8, 10);
                    } else {
                      return value?.substring(5, 7);
                    }
                  },
                },
              },
            ],
            yAxis: [
              {
                type: 'value',
                name: `${intl.formatMessage({
                  id: 'bigdata.unitS',
                })}(kWh)`,
                nameTextStyle: {
                  color: '#222',
                  align: 'left',
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisTick: {
                  show: true,
                  inside: true,
                },
                splitLine: {
                  show: !isEmpty,
                  lineStyle: {
                    type: 'dashed',
                  },
                },
                axisLabel: {
                  color: '#222',
                },
              },
            ],
            series: (pageData?.yData || []).map((item) => {
              return {
                name: item.deviceName,
                type: 'bar',
                data: item.points?.length ? [...item.points.map((res) => res.yaxis)] : [],
                smooth: true,
                symbol: 'none',
              };
            }),

            graphic: [
              {
                type: 'image',
                silent: true,
                style: {
                  image: require('@/assets/img/empty.png'),
                  width: 180,
                  height: 120,
                },
                bounding: 'raw',
                top: 'center',
                left: 'center',
                invisible: !isEmpty,
              },
              {
                type: 'text',
                left: 'center',
                top: 260,
                silent: true,
                invisible: !isEmpty,
                style: {
                  fill: '#222',
                  text: intl.formatMessage({ id: 'global.noDataYet' }),
                  fontFamily: 'Microsoft YaHei',
                  fontSize: '14px',
                },
              },
            ],
          }}
        />
      </Spin>
    </div>
  );
};
export default TableList;
